package com.wxx.shares.changes;

import com.wxx.util.SeleniumDownloader;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Task;

import java.util.ArrayList;
import java.util.List;

/**
 * // #格式：//+标签名+[@属性(例如，id,name,class)="属性对应的值"]
 */
public class SharesChangeDownloader extends SeleniumDownloader {
    List<List<SharesChangeEntity>> dataList = new ArrayList<>();
    @Override
    public Page download(Request request, Task task) {
        try {
            webDriver.get(request.getUrl());

            String name = "";
            if (request.getUrl().contains("zs000001")) {
                name = "上证指数";
            } else {
                // 获取公司名称
                List<WebElement> nameList = webDriver.findElementById("Column_Navigation").findElements(By.tagName("a"));
                if (nameList != null && !nameList.isEmpty()) {
                    name = nameList.get(nameList.size() - 1).getText();
                }
            }

            WebElement tableElement = webDriver.findElementById("dt_1").findElement(By.tagName("tbody"));
            List<SharesChangeEntity> sharesEntityList = new ArrayList<>();
            for (WebElement trElement: tableElement.findElements(By.tagName("tr"))) {
                List<WebElement> tdElementList = trElement.findElements(By.tagName("td"));
                System.out.println("元素是：" + name + "   " + tdElementList.get(0).getText() + "  " + tdElementList.get(2).getText());
                SharesChangeEntity entity = new SharesChangeEntity();
                entity.name = name;
                entity.range = tdElementList.get(2).getText();
                entity.date = tdElementList.get(0).getText();
                sharesEntityList.add(entity);
                SharesChangeDbManager.getSharesTmpMapper().insert(entity);
            }
            dataList.add(sharesEntityList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void parseData() {
        SharesChangeEntity tableHeader = new SharesChangeEntity();
        for (List<SharesChangeEntity> tmp: dataList) {
        }
    }
}
